<template>
  <div class="org-container">
    <drawer-layout left-width="60%">
      <template v-slot:left="{ setFolded }">
        <fks-query-page
          ref="tree"
          v-loading="loading"
          row-key="id"
          :data="treeData"
          :page="false"
          :current-row-key="currentRowKey"
          :expand-row-keys="defaltExpand"
          :table-name="LANG.ORG_DEPARTMENT"
          :highlight-current-row="true"
          @row-click="rowClick"
          @select="handleSelection"
          @selection-change="handleSelectionChange"
        >
          <template slot="singleSearch">
            <div class="single-searchBox">
              <fks-button
                v-saas:dept="['main', 'notSaas']"
                v-permission="['dept:import']"
                @click="importData"
              >
                <i class="fks-icon-import" />
                <span>{{ LANG.IMPORT }}</span>
              </fks-button>
              <fks-button v-permission="['dept:export']" @click="exportData">
                <i class="fks-icon-export" />
                <span>{{ LANG.EXPORT }}</span>
              </fks-button>
              <fks-button
                v-permission="['dept:add']"
                v-saas:dept="['main', 'notSaas']"
                type="primary"
                icon="fks-icon-plus"
                @click="addHandler"
              >
                <span>{{ LANG.ADD }}</span>
              </fks-button>
            </div>
          </template>
          <template>
            <fks-table-column type="selection" width="55" />
            <fks-table-column
              prop="name"
              :label="LANG.DEPTNAME"
              header-align="center"
              min-width="250px"
              align="left"
              is-link
              @link="viewHandler"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.content.name }}</span>
              </template>
            </fks-table-column>
            <fks-table-column
              prop="entName"
              :label="LANG.MEMBERNUMBER"
              align="center"
            >
              <template slot-scope="scope">
                {{ scope.row.content.memberNum }}
              </template>
            </fks-table-column>
            <fks-table-column prop="entName" :label="LANG.REMARK" align="left">
              <template slot-scope="scope">
                {{ scope.row.content.entName }}
              </template>
            </fks-table-column>
            <fks-table-column
              v-if="saasPermission(['main', 'notSaas'], 'org')"
              :label="LANG.OPERATION"
              align="left"
              width="240"
            >
              <span slot-scope="scope">
                <fks-button
                  v-permission="['dept:addChild']"
                  type="text"
                  @click="addSubChildHandler(scope.row.content)"
                  >{{ LANG.ADD_SUBDEPT }}</fks-button
                >
                <fks-button
                  v-permission="['dept:edit']"
                  type="text"
                  @click="editHandler(scope.row.content)"
                  >{{ LANG.EDIT }}</fks-button
                >
                <fks-button
                  v-permission="['dept:delete']"
                  danger-text
                  @click="delHandler(scope.row)"
                  >{{ LANG.DELETE }}</fks-button
                >
              </span>
            </fks-table-column>
          </template>
        </fks-query-page>
      </template>
      <template #right>
        <member-table
          :org-id.sync="orgId"
          :org-name="orgName"
          @refresh="getData"
        />
      </template>
    </drawer-layout>
    <org-info
      :visible.sync="dialogVisible"
      :title="title"
      :data="orgData"
      :tree-data="copyTreeData"
      @refresh="getData()"
    />

    <import-org
      :visible.sync="importVisible"
      :flag="importFlag"
      @fetchData="getData"
    />
  </div>
</template>
<script>
import * as orgApi from "./api";
import Mix from "@/mixins/module";
import orgInfo from "./DeptInfo/index";
import importOrg from "@/modules/System/User/Import";
import { exportFile } from "@/utils/file";
import DrawerLayout from "@/components/DrawerLayout";
import memberTable from "./MemberTable";

export default {
  name: "Department",
  components: {
    orgInfo,
    importOrg,
    DrawerLayout,
    memberTable,
  },
  mixins: [Mix],
  data() {
    return {
      loading: false,
      orgData: {},
      title: "",
      deleteConfirm: "",
      dialogVisible: false,
      memberVisible: false,
      memberData: {},
      defaltExpand: [],
      treeData: [],
      copyTreeData: [],
      exportOrg: [],
      importVisible: false,
      importFlag: "org",
      currentRowKey: "",
      orgId: "",
      orgName: "",
    };
  },
  computed: {
    portalId() {
      return this.$store.state.portal.id;
    },
  },
  created() {
    this.getData();
  },
  methods: {
    rowClick(row) {
      this.currentRowKey = row.id;
      this.orgId = row.id;
      this.orgName = row.content.name;
    },
    //选中菜单
    handleSelection(select, row) {
      if (!row.children) {
        return false;
      }
      if (this.$refs.tree.$refs.table.selection.includes(row)) {
        this.checkRow(row.children, true);
      } else {
        this.checkRow(row.children, false);
      }
    },
    //选中递归
    checkRow(data, bool) {
      data.forEach((item) => {
        this.$refs.tree.$refs.table.toggleRowSelection(item, bool);
        if (item.children) {
          this.checkRow(item.children, bool);
        }
      });
    },
    handleSelectionChange() {
      this.exportOrg = this.$refs.tree.$refs.table.selection;
    },
    importData() {
      this.importVisible = true;
    },
    //导出数据
    exportData() {
      if (this.exportOrg.length > 0) {
        let exportOrgIdList = [];
        this.exportOrg.forEach((item) => {
          exportOrgIdList.push(item.content.id);
        });
        orgApi
          .exportOrg(exportOrgIdList)
          .then((res) => {
            if (res.request.response.type == "application/json") {
              let fileReader = new FileReader();
              fileReader.readAsText(res.data);
              let that = this;
              fileReader.onload = function (result) {
                let jsondata = JSON.parse(result.target.result);
                if (jsondata.status) {
                  that.$message.success(that.LANG.EXPORT_SUCCESS);
                } else {
                  that.$message.error(that.LANG.EXPORT_FAILED);
                }
              };
            } else {
              // 'application/vnd.ms-excel'
              exportFile(res);
              this.$message.success(this.LANG.EXPORT_SUCCESS);
            }
          })
          .catch(() => {});
      } else {
        this.$message.warning(this.LANG.EXPORT_TIP);
      }
    },
    //获取组织机构数据
    @permission("dept:query")
    getData() {
      this.loading = true;
      orgApi
        .getOrgs(this.portalId)
        .then((res) => {
          this.loading = false;
          if (res.status) {
            if (res.data[0]) {
              if (!this.currentRowKey) {
                this.currentRowKey = res.data[0].id;
              }
              this.defaltExpand.push(res.data[0].id);
              if (res.data[0].id == this.currentRowKey) {
                this.orgName = res.data[0].content.name;
                this.orgId = res.data[0].content.orgNo;
              }
            }
            this.treeData = res.data;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    delOrgData(orgData, orgNo) {
      if (orgData[0].id == orgNo) return orgData;
      if (orgData[0]?.children && orgData[0].children.length > 0) {
        let currentOrgData = {};
        orgData[0].children.forEach((item) => {
          if (item.id == orgNo) {
            currentOrgData = item;
          } else {
            if (item.children && item.children.length > 0) {
              this.delOrgData(item.children, orgNo);
            }
          }
        });
        return currentOrgData;
      }
    },
    //打开管理成员弹窗
    handleMember(row) {
      this.memberVisible = true;
      this.memberData = JSON.parse(JSON.stringify(row));
    },
    //打开编辑组织机构弹窗
    editHandler(data) {
      this.orgData = JSON.parse(JSON.stringify(data));
      this.dialogVisible = true;
      this.title = this.LANG.EDIT;
    },
    viewHandler({ row }) {
      this.orgId = row.id;
      this.orgName = row.content.name;
    },
    // 打开新增组织机构弹窗
    addHandler() {
      this.dialogVisible = true;
      this.title = this.LANG.ADD;
      this.orgData = {};
      this.copyTreeData = this.treeData;
    },
    //打开新增子部门弹窗
    addSubChildHandler(data) {
      this.title = this.LANG.ADD_SUBDEPT;
      this.orgData = JSON.parse(JSON.stringify(data));
      this.dialogVisible = true;
    },
    //打开删除组织机构二次确认弹窗
    delHandler(data) {
      orgApi
        .getUser({ orgNo: data.content.orgNo })
        .then((res) => {
          if (res.status && res.data.length > 0) {
            this.deleteConfirm = this.LANG.DELETE_DEPARTMENT_CONFIRM;
            this.deleteOrg(data);
          } else {
            this.deleteConfirm = this.LANG.DELETE_CONFIRM;
            this.deleteOrg(data);
          }
        })
        .catch(() => {});
    },
    // 删除组织机构
    @monitor("click", "删除组织机构")
    deleteOrg(data) {
      this.$confirm(this.deleteConfirm, {
        title: this.LANG.TIPS,
        type: "warning",
        confirmButtonText: this.LANG.DELETE,
        cancelButtonText: this.LANG.CANCEL,
        confirmButtonClass: "fks-button--danger",
        deleteMode: true,
      })
        .then(() => {
          orgApi
            .deleteOrg(data.content.id)
            .then((res) => {
              if (res.status) {
                this.$message.success(this.LANG.DELETE_SUCCESS);
                //删除后刷新
                this.getData(true);
              }
            })
            .catch(() => {});
        })
        .catch(() => {});
      return { id: data.content.id };
    },
  },
};
</script>
<style lang="scss" scoped>
.listContant {
  display: inline-block;
  width: 100%;
  height: 100%;
}
.org-container {
  width: 100%;
  min-width: 312px;
  height: 100%;
  background: #f1f2f6;
  ::v-deep .right {
    width: calc(40% - 8px) !important;
    margin-left: 8px;
  }
  ::v-deep .fks-table__body-wrapper {
  }
}
</style>